#made during google cssi 2011
#Backend by Nicholas Laferriere
#frontend by Nora Grossman
import urllib
import os
import logging
import time
import string
import random
import randomintgen
import codeown

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext.webapp import template    

alphabet = "abcdefghijklmnopqrstuvwxyz 1234567890"

class idnumberd(db.Model):
  keynumber = db.StringProperty(required=True)
  keystring = db.StringProperty(required=True)

def rot():
     student = idnumberd(keynumber='13', keystring='nopqrstuvwxyzabcdefghijklm 0123456789')
     student.put()


class MainHandler(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'home.html')
        self.response.out.write(template.render(path, template_values))

class EncodeHandler(webapp.RequestHandler):
    def get(self):
        if self.request.get('input'):
          return self.post()
        rot()
        inputText = 'Write your text here'     
        output = ''
        id_number = '13'
        template_values = {'inputText' : inputText, 'output' : output, 'id_number' : id_number} 
        path = os.path.join(os.path.dirname(__file__), 'encode.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        rot()
        inputText = self.request.get('input')
        id_number = self.request.get('id_number')
        id_value = idnumberd.all()
        presendid_number = id_value.filter('keynumber =', id_number)
        presendidnumber = presendid_number.fetch(limit=1)
        sendidnumber = presendidnumber[0].keystring
        output = codeown.encode(inputText, sendidnumber)
        template_values = {'inputText' : inputText, 'output' : output} 
        path = os.path.join(os.path.dirname(__file__), 'encode.html')
        self.response.out.write(template.render(path, template_values))

class DecodeHandler(webapp.RequestHandler):
    def get(self):
        if self.request.get('input'):
          return self.post()
        inputText = 'Write your encrypted text here'
        output = ''
        id_number = '13'
        template_values = {'inputText' : inputText, 'output' : output, 'id_number' : id_number}
        path = os.path.join(os.path.dirname(__file__), 'decode.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        inputText = self.request.get('input')
        id_number = self.request.get('id_number')
        id_value = idnumberd.all()
        presendid_number = id_value.filter('keynumber =', id_number)
        presendidnumber = presendid_number.fetch(limit=1)
        sendidnumber = presendidnumber[0].keystring
        output = codeown.decode(inputText, sendidnumber)
        template_values = {'inputText' : inputText, 'output' : output, 'id_number' : id_number} 
        path = os.path.join(os.path.dirname(__file__), 'decode.html')
        self.response.out.write(template.render(path, template_values))

class CreateHandler(webapp.RequestHandler):
    def post(self):
        template_values = {}	    
        newKey = ''
        newKeyList = []
        newKeyList.append(self.request.get('a'))
        newKeyList.append(self.request.get('b'))
        newKeyList.append(self.request.get('c'))
        newKeyList.append(self.request.get('d'))
        newKeyList.append(self.request.get('e'))
        newKeyList.append(self.request.get('f'))
        newKeyList.append(self.request.get('g'))
        newKeyList.append(self.request.get('h'))
        newKeyList.append(self.request.get('i'))
        newKeyList.append(self.request.get('j'))
        newKeyList.append(self.request.get('k'))
        newKeyList.append(self.request.get('l'))
        newKeyList.append(self.request.get('m'))
        newKeyList.append(self.request.get('n'))
        newKeyList.append(self.request.get('o'))
        newKeyList.append(self.request.get('p'))  
        newKeyList.append(self.request.get('q'))
        newKeyList.append(self.request.get('r'))
        newKeyList.append(self.request.get('s'))
        newKeyList.append(self.request.get('t'))
        newKeyList.append(self.request.get('u'))
        newKeyList.append(self.request.get('v'))
        newKeyList.append(self.request.get('w'))
        newKeyList.append(self.request.get('x'))
        newKeyList.append(self.request.get('y'))
        newKeyList.append(self.request.get('z'))
        newKeyList.append(' ')
        newKeyList.append(self.request.get('0'))
        newKeyList.append(self.request.get('1'))
        newKeyList.append(self.request.get('2'))
        newKeyList.append(self.request.get('3'))
        newKeyList.append(self.request.get('4'))
        newKeyList.append(self.request.get('5'))
        newKeyList.append(self.request.get('6'))
        newKeyList.append(self.request.get('7'))
        newKeyList.append(self.request.get('8'))
        newKeyList.append(self.request.get('9'))

        for key in newKeyList:
          if key in alphabet and not in newKey:
              newKey += key
          else:
              path = os.path.join(os.path.dirname(__file__), 'error.html')
              self.response.out.write(template.render(path, template_values))

        if len(newKey) != 37:
              path = os.path.join(os.path.dirname(__file__), 'error.html')
              self.response.out.write(template.render(path, template_values))

        myNewKeyNum = str(random.randint(100, 99999))
        logging.info(newKey)
        logging.info(myNewKeyNum)
        myCode = idnumberd(keynumber= myNewKeyNum, keystring= newKey)
        myCode.put()
        template_values = {'key' : myNewKeyNum, 'keyString' : newKey} 

        path = os.path.join(os.path.dirname(__file__), 'create.html')
        self.response.out.write(template.render(path, template_values))

    def get(self):
        inputText = self.request.get('input')
        self.response.out.write(self.request)
        template_values = {} 
        path = os.path.join(os.path.dirname(__file__), 'create.html')
        self.response.out.write(template.render(path, template_values))
   	

class InstructionsHandler(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'instructions.html')
        self.response.out.write(template.render(path, template_values))

class ErrorHandler(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'error.html')
        self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication([('/encode.*', EncodeHandler),
                                        ('/decode.*', DecodeHandler),
                                        ('/create.*', CreateHandler),
                                        ('/error.*', ErrorHandler),
                                        ('/instructions.*', InstructionsHandler),
                                        ('/.*', MainHandler)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  rot()
  main()

